package com.coder._02.server;

import com.coder._02.sequence.ServerSequenceNum02;
import com.coder._02.client.Time;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 服务器解码器
 *
 * 连接建立时，发送当前时间
 */
public class TimeServerHandlerPOJO extends ChannelInboundHandlerAdapter {

    /**
     * 连接建立并且准备进行通信时被调用
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(final ChannelHandlerContext ctx) throws Exception {
        ServerSequenceNum02.num(TimeServerHandlerPOJO.class);
        // 发送当前时间信息
        ChannelFuture future = ctx.write(new Time());
        // 发送完毕之后，关闭channel
        future.addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}
